<template>
  <div class="basic-content">
    <!-- tool start -->
    <el-form ref="form" :model="formDetail" :rules="ruleForm" label-width="120px">
      <el-row>
        <el-col :span="8" v-if="this.$attrs.detail">
          <el-form-item :label="$t('m.otherstore.storagecode')">
            <el-input maxlength="20" show-word-limit v-model="formDetail.storagecode" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.in.consignor')" prop="consignorid">
            <template v-if="componentState">
              <el-select v-model="formDetail.consignorname" disabled></el-select>
            </template>
            <template v-else>
              <el-select v-model="formDetail.consignorid" filterable :placeholder="$t('m.choose')+$t('m.in.consignor')">
                <el-option v-for="(item,index) in consignorOptions" :key="index" :label="item.consignorname" :value="item.consignorid" :disabled="item.disabled"></el-option>
              </el-select>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.in.suppliername')" prop="supplierid">
            <template v-if="componentState">
              <el-select v-model="formDetail.suppliername" disabled></el-select>
            </template>
            <template v-else>
              <el-select v-model="formDetail.supplierid" filterable :placeholder="$t('m.choose')+$t('m.in.suppliername')">
                <el-option v-for="(item,index) in supplierOptions" :key="index" :label="item.suppliername" :value="item.supplierid"></el-option>
              </el-select>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('m.otherstore.currency')" prop="currencyid">
            <template v-if="componentState">
              <el-select v-model="formDetail.currency" disabled></el-select>
            </template>
            <template v-else>
              <el-select v-model="formDetail.currencyid" filterable :placeholder="$t('m.choose')+$t('m.otherstore.currency')">
                <el-option v-for="(item,index) in currencyOptions" :key="index" :label="item.typevalue" :value="item.typevalueid"></el-option>
              </el-select>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="$attrs.detail&&$attrs.detail.state===3">
          <el-form-item :label="$t('m.otherstore.indate')" class="date-picker">
            <el-date-picker v-model="$attrs.detail.auditdate" disabled></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('m.remark')" prop="remark">
            <el-input type="textarea" maxlength="100" show-word-limit v-model="formDetail.remark" :rows="2" :disabled="componentState"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- tool end -->

    <!-- table start -->
    <el-form ref="table" :model="tableDetail" :rules="ruleTable" size="mini">
      <el-row class="container-table">
        <el-col :span="24">
          <el-table class="table-wrap" :data="tableDetail.tableData" stripe empty-text fit>
            <el-table-column align="center" :label="$t('m.index')" width="50">
              <template slot-scope="scope">
                <el-form-item>{{scope.$index+1}}</el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="sku" width="146px">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input v-model.trim="scope.row.productspeccode" maxlength="50" show-word-limit :placeholder="$t('m.enter')+'SKU'" @change="getProductDetail(scope.row.productspeccode,scope.$index)" :disabled="componentState"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="suppliercode" label="supplierCode">
              <template slot-scope="scope">
                <el-form-item>{{scope.row.suppliercode}}</el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="productname" :label="$t('m.in.productname')" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item>{{scope.row.productname}}</el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="productspec" :label="$t('m.in.productspec')" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-form-item>{{scope.row.productspec}}</el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" width="100" prop="quantity" :label="$t('m.otherstore.inquantity')">
              <template slot-scope="scope">
                <el-form-item v-for="(item,index) in scope.row.storageQuantitys" :key="index" :prop="'tableData.'+scope.$index+'.storageQuantitys.'+index+'.quantity'" :rules="ruleTable.quantity">
                  <el-input v-model="item.quantity" :disabled="componentState" maxlength="5" v-input-valid></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="100" prop="unitprice" :label="$t('m.otherstore.unitprice')">
              <template slot-scope="scope">
                <el-form-item v-for="(item,index) in scope.row.storageQuantitys" :key="index" :prop="'tableData.'+scope.$index+'.storageQuantitys.'+index+'.unitprice'" :rules="ruleTable.unitprice">
                  <el-input maxlength="20" v-model="item.unitprice" :disabled="componentState" v-input-valid:price></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 批次属性 start -->
            <el-table-column align="center" :label="$t('m.strategy.batch')" width="160">
              <template slot-scope="scope">
                <el-form-item
                  v-for="(item,index) in scope.row.batchattr.filter((item)=>item.enable)"
                  v-show="item.enable"
                  :key="index"
                  :label="item.label"
                  :prop="`${item.enable?'tableData.'+scope.$index+'.batchattr.'+index+'.value':''}`"
                  :rules="ruleTable[item.validateFn]"
                  :required="item.inputtype===1"
                >
                  <!--  :prop="`${item.enable?'tableData.'+scope.$index+'.batchattr.'+index+'.value':''}`"
                  :rules="ruleTable[item.validateFn]"-->
                  <!-- format:1.字符串输入框；2.数字输入框；3.日期选择；4.日期时间选择 -->
                  <template v-if="item.format===1">
                    <el-input maxlength="20" :disabled="item.label==='入库日期'||item.inputtype===0" v-model.trim="scope.row.batchattr[index].value" @focus="getBatchattr(scope.$index,index)" @blur="handleInputTime(scope.$index,index)"></el-input>
                  </template>
                  <template v-if="item.format===2">
                    <el-input maxlength="20" :disabled="item.label==='入库日期'||item.inputtype===0" v-model.number.trim="scope.row.batchattr[index].value" @focus="getBatchattr(scope.$index,index)" @blur="handleInputTime(scope.$index,index)"></el-input>
                  </template>
                  <template v-if="item.format===3">
                    <el-date-picker
                      v-model="scope.row.batchattr[index].value"
                      type="date"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :disabled="item.label==='入库日期'||item.inputtype===0"
                      :placeholder="$t('m.in.choosedate')"
                      @focus="getBatchattr(scope.$index,index)"
                      @change="handlePickTime(scope.$index,index)"
                    ></el-date-picker>
                  </template>
                  <template v-if="item.format===4">
                    <el-date-picker
                      v-model="scope.row.batchattr[index].value"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      :disabled="item.label==='入库日期'||item.inputtype===0"
                      :placeholder="$t('m.in.choosedate')"
                      default-time="00:00:00"
                      @focus="getBatchattr(scope.$index,index)"
                      @change="handlePickTime(scope.$index,index)"
                    ></el-date-picker>
                  </template>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- 批次属性 end -->
            <el-table-column align="center" prop="locationcode" :label="$t('m.otherstore.inlocationcode')" width="146px">
              <template slot-scope="scope">
                <el-form-item v-for="(item,index) in scope.row.storageQuantitys" :key="index" :prop="'tableData.'+scope.$index+'.storageQuantitys.'+index+'.locationid'" :rules="ruleTable.locationid">
                  <template v-if="componentState">
                    <el-select v-model="item.locationcode" disabled></el-select>
                  </template>
                  <template v-else>
                    <el-input :placeholder="$t('m.pleasechooselocaiton')" v-model="item.locationcode" clearable readonly @focus="showLocationList(scope.row.productspeccode,item.quantity,scope.$index,index)" />
                  </template>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="40" v-if="!componentState">
              <template slot-scope="scope">
                <el-form-item v-for="(item,index) in scope.row.storageQuantitys" :key="index">
                  <div class="btn-wrap">
                    <el-button :type="index?'danger':'success'" class="add icon-btn" circle @click="handleStorageDetail(item,index,scope.$index)">{{index?'-':'+'}}</el-button>
                  </div>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('m.operation')" v-if="!componentState">
              <template slot-scope="scope">
                <el-form-item>
                  <el-button type="danger" @click="beforeRemoveRow(scope.$index)" v-show="tableDetail.tableData.length>1">{{$t('m.delete')}}</el-button>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <el-row v-if="!componentState">
        <el-col :span="24" align="left">
          <el-button size="mini" type="primary" @click="addRow">{{$t('m.otherstore.adddetail')}}</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- table end -->

    <el-dialog :title="$t('m.noticemessage')" :visible.sync="tipsDialogVisible" width="30%" center append-to-body>
      <p align="center">{{$t('m.deleteAlert')}}</p>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="tipsDialogVisible=false">{{$t('m.cancel')}}</el-button>
        <el-button size="mini" type="primary" @click="removeRow">{{$t('m.confirm')}}</el-button>
      </span>
    </el-dialog>

    <!-- 选择库位dialog start -->
    <locationListPopup v-if="locationListPopupVisible" :popupVisible="locationListPopupVisible" :config="locationConfig" @submit="setLocation" @close="locationListPopupVisible=false"></locationListPopup>
    <!-- 选择库位dialog end -->
  </div>
</template>
<script>
import {
  formValidate,
  tableValidate
} from '@/assets/mixins/rule/storage-add-validate'
import common from '@/utils/common'
export default {
  name:'storage-basic-content',
  mixins:[formValidate, tableValidate],
  data(){
    return {
      formDetail:{
        consignorid:'', // 货主
        supplierid:'', // 供应商
        currencyid:'', // 币种id
        remark:''
      },
      consignorOptions:[], // 货主列表
      supplierOptions:[], // 供应商列表
      currencyOptions:[], // 币种列表

      storageInitItem:{
        suppliercode:null, // 供应商号
        productid:'', // 产品id
        productname:'', // 产品名称
        productspec:'', // 产品规格
        productspeccode:'', // sku
        storageQuantitys:[],
        batchattr:[] // 批次属性
      },
      detailsInitItem:{
        quantity:'', // 入库数量
        unitprice:'', // 单价
        locationcode:'', // 入库库位
        locationid:'' // 库位id
      },
      detail:{},
      isGetedBatchattr:false, // 是否已经获取sku的批次属性限制信息

      activebatchattrIndex:0,
      tableDetail:{
        tableData:[]
      },
      indexOptions:{}, // 记录当前操作的是那一条数据的locationcode
      locationConfig:{}, // 需要传递给locations-list组件的参数

      removeStorageDetailIndex:0, // 当前删除的入库明细
      tipsDialogVisible:false, // 控制提示框显示隐藏
      locationListPopupVisible:false, // 控制选择库位dialog显示隐藏

      pickerOptions:{
        disabledDate(time){
          return time.getTime() > Date.now()
        }
      }
    }
  },
  mounted(){
    // 新增 || 编辑
    if (!this.componentState){
      this.getCurrency()
      this.getSupplier()
      this.getConsignor()
      this.storageInitItem.storageQuantitys.push(
        this.cloneObject(this.detailsInitItem)
      )
    }
    if (!this.$attrs.detail){
      // 新增
      this.addRow() // 默认给表格添加一条数据
    } else {
      // 编辑 || 审核 || 查询
      this.formDetail = this.$attrs.detail
      this.tableDetail.tableData = this.$attrs.detail.otherStorageDetails.reduce((prev, next) => {
        let item = this.cloneObject(next)
        let fixedType = ['生产日期', '到期日期', '入库日期']
        item.batchattr = JSON.parse(item.batchattr).map((item) => {
          if (item.label === fixedType[2]) item.value = `${common.timestampSimple(new Date())} 00:00:00`
          // format:1.字符串输入框；2.数字输入框；3.日期选择；4.日期时间选择
          // inputtype:0.禁用；1.必填；2.选填；3.只读；
          switch (item.format){
          case 1:
            item.validateFn = item.inputtype === 1 ?
              fixedType.includes(item.label) ? 'stringRequiredFixedTypeValidate' : 'stringRequiredValidate'
              : 'stringValidate'
            break
          case 2:
            item.validateFn = item.inputtype === 1 ? 'numberRequiredValidate' : 'numberValidate'
            break
          case 3:
            item.validateFn = item.inputtype === 1 ? 'dateRequiredValidate' : 'dateValidate'
            break
          case 4:
            item.validateFn = item.inputtype === 1 ? 'dateTimeRequiredValidate' : 'dateTimeValidate'
            break
          default:
            item.validateFn = ''
          }
          return item
        })
        return prev.concat(item)
      }, [])
    }
  },
  computed:{
    componentState(){ // true：审核
      return 'isReview' in this.$attrs
    },
    // 总数量
    totalAmount(){
      let result = 0
      for (let i = 0;i < this.tableDetail.tableData.length;i++){
        for (let j = 0;j < this.tableDetail.tableData[i].storageQuantitys.length;j++){
          let quantity = parseInt(this.tableDetail.tableData[i].storageQuantitys[j].quantity)
          result += quantity
        }
      }
      return result
    },
    // 总价格
    totalPrice(){
      let result = 0
      for (let i = 0;i < this.tableDetail.tableData.length;i++){
        for (let j = 0;j < this.tableDetail.tableData[i].storageQuantitys.length;j++){
          let quantity = parseInt(this.tableDetail.tableData[i].storageQuantitys[j].quantity)
          let unitprice = parseFloat(this.tableDetail.tableData[i].storageQuantitys[j].unitprice)
          result += quantity * unitprice
        }
      }
      return result
    }
  },
  components:{
    locationListPopup:() => import('@/components/common/location-list')
  },
  methods:{
    // 获取货主
    getConsignor(){
      let options = {
        method:'get',
        url:`/consignor/list`
      }
      this.$axios(options).then(({ data }) => {
        this.consignorOptions = data
        if (this.$attrs.detail){ // 盘点用户录入的货主是否被禁用，如果被禁用了，添加到consignorOptions里
          let { consignorname, consignorid } = this.$attrs.detail
          let result = this.consignorOptions.some((item) => {
            return item.consignorid === consignorid
          })
          if (!result) this.consignorOptions.push({ consignorname, consignorid, disabled:true })
        }
      })
    },
    // 获取币种
    getCurrency(){
      let options = {
        method:'get',
        url:`/typevalue/list?name=币种`
      }
      this.$axios(options).then(({ data }) => {
        this.currencyOptions = data
      })
    },
    // 获取供应商
    getSupplier(){
      let options = {
        method:'get',
        url:`/supplier/list`
      }
      this.$axios(options).then(({ data }) => {
        this.supplierOptions = data
        if (this.$attrs.detail){ // 盘点用户录入的供应商是否被禁用，如果被禁用了，添加到supplierOptions里
          let { suppliername, supplierid } = this.$attrs.detail
          let result = this.supplierOptions.some((item) => {
            return item.supplierid === supplierid
          })
          if (!result) this.supplierOptions.push({ suppliername, supplierid, disabled:true })
        }
      })
    },
    // (失焦event)根据sku获取商品明细
    getProductDetail(code, index){
      if (!code) return this.callbackMessage(this.$t('m.enter') + 'SKU')
      let options = {
        method:'get',
        url:`/productinfo/sku?sku=${code}`
      }
      this.$axios(options).then(({ data }) => {
        this.detail = data.productdto // 获取sku的禁收日期限制
        let detail = {}
        if (data.productdto.batchattr === '[{}]' || !data.productdto.batchattr) data.productdto.batchattr = '[]'
        let fixedType = ['生产日期', '到期日期', '入库日期']
        let batchattr = JSON.parse(data.productdto.batchattr).map((item) => {
          if (item.label === fixedType[2]) item.value = `${common.timestampSimple(new Date())} 00:00:00`
          // format:1.字符串输入框；2.数字输入框；3.日期选择；4.日期时间选择
          // inputtype:0.禁用；1.必填；2.选填；3.只读；
          switch (item.format){
          case 1:
            item.validateFn = item.inputtype === 1 ?
              fixedType.includes(item.label) ? 'stringRequiredFixedTypeValidate' : 'stringRequiredValidate'
              : 'stringValidate'
            break
          case 2:
            item.validateFn = item.inputtype === 1 ? 'numberRequiredValidate' : 'numberValidate'
            break
          case 3:
            item.validateFn = item.inputtype === 1 ? 'dateRequiredValidate' : 'dateValidate'
            break
          case 4:
            item.validateFn = item.inputtype === 1 ? 'dateTimeRequiredValidate' : 'dateTimeValidate'
            break
          default:
            item.validateFn = ''
          }
          return item
        })

        detail.suppliercode = data.productSkuList[0].suppliercode || null
        detail.productname = data.productdto.productname
        detail.productspec = data.productSkuList[0].fullspec
        detail.productid = data.productdto.productid
        detail.batchattr = batchattr || []
        this.assignment(index, detail)
      }).catch(({ code }) => {
        if (code === 9999){
          // 当sku置空后，其子容器内所有内容都要置空
          for (const key in this.tableDetail.tableData[index]){
            if (key === 'batchattr' || key === 'storageQuantitys'){
              this.tableDetail.tableData[index][key] = []
            } else {
              this.tableDetail.tableData[index][key] = ''
            }
          }
          this.tableDetail.tableData[index].storageQuantitys.push(this.cloneObject(this.detailsInitItem))
        }
      })
    },
    // 获取当前获得焦点的sku的批次属性限制信息
    getBatchattr(index){
      let sku = this.tableDetail.tableData[index].productspeccode
      let options = {
        method:'get',
        url:`/productinfo/sku?sku=${sku}`
      }
      this.isGetedBatchattr = false
      this.$axios(options).then(({ data }) => {
        this.detail = data.productdto // 获取sku的禁收日期限制
        this.isGetedBatchattr = true
      })
    },
    // 必须等待完成获取sku的批次属性限制信息，才能进行设置
    handleInputTime(index, __index){
      if (this.isGetedBatchattr){
        this.inputTime(index, __index)
      } else {
        this.callbackMessage(this.$t('m.otherstore.forbidden1'))
      }
    },
    handlePickTime(index, __index){
      if (this.isGetedBatchattr){
        this.pickTime(index, __index)
      } else {
        this.callbackMessage(this.$t('m.otherstore.forbidden1'))
      }
    },
    // 根据sku给table[index]赋值
    assignment(index, options){
      let result = {...this.tableDetail.tableData[index], ...options}
      this.$set(this.tableDetail.tableData, index, result)
    },
    // 显示选择库位的dialog
    showLocationList(sku, quantity, scopeIndex, index){
      if (!sku) return this.callbackMessage(this.$t('m.skuNotNull'))
      if (!quantity) return this.callbackMessage(this.$t('m.putInStorageQuantityNotNull'))
      let typelist = [1, 2, 3].join(',') // [1:收货区,2:存货区,3:拣货区,4:不良品区,5:退货区]
      this.locationConfig = {
        params:{ sku, quantity, typelist }
      }
      this.indexOptions.scopeIndex = scopeIndex
      this.indexOptions.index = index

      this.locationListPopupVisible = true
    },
    // 设置选中的库位信息
    setLocation(location){
      let target = this.tableDetail.tableData[this.indexOptions.scopeIndex].storageQuantitys[this.indexOptions.index]
      this.$set(target, 'locationcode', location.locationcode)
      this.$set(target, 'locationid', location.locationid)
      this.locationListPopupVisible = false
    },
    // 添加or删除容器详情
    handleStorageDetail(item, index, scopeIndex){
      if (index){
        // 删除操作(默认保留一项)
        this.$delete(this.tableDetail.tableData[scopeIndex].storageQuantitys, index)
      } else {
        // 添加操作
        this.tableDetail.tableData[scopeIndex].storageQuantitys.push(this.cloneObject(this.detailsInitItem))
      }
    },
    // 添加入库明细
    addRow(){
      this.tableDetail.tableData.push(this.cloneObject(this.storageInitItem))
    },
    beforeRemoveRow(index){
      this.removeStorageDetailIndex = index
      this.tipsDialogVisible = true
    },
    // 删除入库明细
    removeRow(){
      this.tipsDialogVisible = false
      this.$delete(this.tableDetail.tableData, this.removeStorageDetailIndex)
    },
    validateFloatNumber(index, __index){
      this.$set(this.tableDetail.tableData[index].storageQuantitys[__index], 'unitprice', this.tableDetail.tableData[index].storageQuantitys[__index].unitprice.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, ''))
    }
  }
}
</script>
<style lang="scss" scoped>
.date-picker ::v-deep .el-date-editor--date {
  width: 100%;
}
.container-table ::v-deep {
  .el-table {
    margin-bottom: 22px;
  }
}
.btn-wrap {
  height: 28px;
  margin-top: 18px;
  display: flex;
  align-items: center;
  &:first-child {
    margin-top: 0;
  }
  .icon-btn {
    margin-left: 0;
  }
}
</style>